<template>
  <div id="printDOM" class="medicalRecord-container" ref="medicalRecordView">
    <div class="mr-header">
      <div class="search-grip">
        <span>病历日期:</span>
        <XMDatePicker
          :disabled="disabledTime"
          type="date"
          disabledDateT="after"
          v-model="d.recordDate"
          label="选择开始时间"
          prop="fillingTime"
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 180px"
          @timeChange="timeChange"
        ></XMDatePicker>
      </div>
      <XmDropdown
        v-if="!isRiskRx"
        :disabled="d.disabled"
        :titles="d.modes"
        :value="d.mode"
        @changeTitle="modeChange"
      >
        <div class="iconClass" :class="{ 'is-complete': d.disabled }"></div>
      </XmDropdown>
      <el-button
        v-if="isHasRisk"
        type="primary"
        style="margin-left: 10px"
        @click="importRiskData"
      >
        导入风险筛查
      </el-button>
      <el-button
        :disabled="d.disabled"
        type="primary"
        v-if="d.docType === 0"
        style="float: right"
        @click="selectTemplate"
      >
        选择模板
      </el-button>
      <XmDropdown
        :disabled="isRiskRx"
        :titles="d.emrDocTypes"
        :value="d.docType"
        @changeTitle="emrChange"
        style="float: right; margin-right: 12px"
      ></XmDropdown>
    </div>
    <PersonInfoCard :id="pid" type="print" v-if="hideButton" />
    <normal
      v-if="d.docType === 0"
      :disabled="d.disabled"
      :id="pid"
      :vid="vid"
      :emrId="d.emrId"
      :docType="d.docType"
      ref="emrRef"
      @toData="toNormalSave"
      @toTemplateSave="toTemplateSave"
    ></normal>
    <asthma
      v-else
      :id="pid"
      :disabled="!!d.disabled"
      :recordDate="d.recordDate"
      :class="{'print-asthma': hideButton}"
      :vid="vid"
      :emrId="d.emrId"
      :docType="d.docType"
      :hide-button="hideButton"
      ref="emrRef"
      @toData="toAsthmaSave"
      @print="print"
    ></asthma>
  </div>
</template>
<script>
import {computed, nextTick, onBeforeMount, reactive, ref, watch} from 'vue'
import asthma from './asthma'
import normal from './normal'
import {useRoute} from 'vue-router'
import {useStore} from 'vuex'
import {getAllTime} from '@/utils/timeTools'
import {load, save, saveNormalTemplate} from '@/api/modules/emr'
import common from '@/utils/common'
import {ElMessage} from 'element-plus'
import moment from 'moment'
import filter from '@/hooks/filter'
import {emrStatus} from '@/hooks/event/useEmr.js'
import {useRouteAndRouter} from '@/hooks/core/useRouteAndRouter.js'
import {saveRisk} from '@/api/modules/risk.js'
import {usePromise} from '@/hooks/core/usePromise.js'
import {isHas} from '../../../utils/validate'
import {cloneDeep} from 'lodash'
import { VuePrintLast } from "vue-print-last";
import PersonInfoCard from "@/views/patientInfo/components/personInfoCard.vue";

export default {
    components: {PersonInfoCard, asthma, normal },
    name: 'medicalRecordView',
    props: { pid: Number, vid: Number },
    emits: ['update:doctype'],
    setup(props, context) {
      // 放在第一行
      const d = reactive({
        mode: 1,
        // 病历时间
        recordDate: getAllTime(),
        // 修改病历时间之前的时间
        oldRecordDate: getAllTime(),
        emrId: null,
        modes: [
          { value: '1', label: '规范用药中' },
          { value: '0', label: '已停用规范控制药物' },
        ],
        emrDocTypes: [],
        treatmentType: null,
        docType: '',
        status: null,
        riskMedicalRecordId: null,
        // mode: '规范用药中',
      })
      const { isRiskRx } = useRouteAndRouter()
      const { to } = usePromise()
      const emrRef = ref(null)
      const route = useRoute()
      watch(
        () => route.query.emrId,
        async (emrId) => {
          if (emrId) {
            d.emrId = emrId
            toLoad(emrId)
          } else {
            // emrRef.value.clear()
          }
        }
      )

      const isHasRisk = computed(() => {
        if (d.riskMedicalRecordId && !isRiskRx.value && !d.disabled) {
          return true
        }
        return false
      })
      /**
       * 1. 只有pid 查询是否为首诊 /medicalRecord/firstDiagnosis
       * or 有pid和emrId 走回显 /medicalRecord/queryInfo
       */
      // 有pid和emrId 查询是否为首诊和病例详情 /medicalRecord/queryInfo 一个接口
      const toLoad = async function () {
        common.XmLoading(true)
        /**
         * riskScreeningType 传递给后端让后端能判断是不是风险筛查界面进入
         */
        const [err, res] = await to(
          load({
            medicalRecordId: route.query.emrId,
            patientId: props.pid,
            docType: route.query.emrId ? null : d.docType,
            riskScreeningType: isRiskRx.value ? 1 : 0,
            recordDate: moment(d.recordDate).format('YYYY-MM-DD HH:mm:ss'),
          })
        )
        common.XmLoading(false)
        if (err) return
        // 例行清理一下缓存中的id
        store.dispatch('emr/clearControlIdAndAcuteId')
        // 更新一下 recordDate
        d.treatmentType = res.data.treatmentType
        d.docType = res.data.docType
        d.riskMedicalRecordId = res.data.riskMedicalRecordId
        if (isHas(res.data.drugOptions)) d.mode = res.data.drugOptions
        if (res.data.recordDate)
          d.recordDate = moment(res.data.recordDate).format(
            'YYYY-MM-DD HH:mm:ss'
          )
        // 拷贝当oldVal用
        d.oldRecordDate = cloneDeep(d.recordDate)
        // if (res.data.riskMedicalRecordId)
        //
        // 保存全局数据
        d.disabled = res.data.status === 2 ? true : false
        d.status = res.data.status

        await nextTick()
        context.emit('update:doctype', d.docType)
        console.log(d.treatmentType, res.data)
        if (emrRef.value) emrRef.value.initEmr(res.data)
        store.dispatch('emr/setEditingStatus', false)

        // 传入备份数据
        store.dispatch('emr/setEmrRecordBirthday', res.data.recordBirthday)
      }

      const toSave = async function (data, isTemplate) {
        const msg = data.status === 2 ? '是否提交' : '是否保存'
        const risk = isRiskRx
        data['recordDate'] = moment(d.recordDate).format('YYYY-MM-DD HH:mm:ss')
        data['drugOptions'] = d.mode
        data['docType'] = d.docType
        if (risk.value) {
          data['historicalVisitRiskId'] = props.vid
          data['riskMedicalRecordId'] = route.query.emrId
        } else {
          data['historicalVisitId'] = props.vid
          data['medicalRecordId'] = route.query.emrId
          data['acuteWheezingActionPlanId'] = store.getters.emrAcuteId
          data['controlActionPlanId'] = store.getters.emrControlId
        }
        data['treatmentType'] = d.treatmentType
        data['riskScreeningType'] = risk.value ? 1 : 0
        if (isImport.value && d.riskMedicalRecordId)
          data['riskMedicalRecordId'] = parseInt(d.riskMedicalRecordId)

        function choice(data) {
          if (isRiskRx.value) {
            return to(saveRisk(data))
          } else {
            return to(save(data, isTemplate))
          }
        }
        await common.syncAlert(msg)
        common.XmLoading(true)
        const [err, res] = await choice(data)
        common.XmLoading()
        if (err) return
        ElMessage.success(res.message)
        if (route.query.emrId) {
          routerFilter({
            delete: 'riskId',
            delete1: 'isRisk',
            emrId: route.query.emrId,
          })
          toLoad()
          // 有emrId后
        } else {
          // TODO 不更新，先换成普通push
          routerFilter({ query: { ...route.query, emrId: res.data } })
        }
        // TODO 这里是不是整个event-bus
        store.dispatch('patient/loadHistoricalVisitInfo', {
          patientId: props.pid,
          type: route.query.vtype,
          pageIndex: 1,
          pageSize: 1000,
          riskScreeningType: 0,
        })

        resetData(data)
      }

      // 重置患者状态，重置编辑格式
      function resetData(data) {
        store.dispatch('patient/loadEmrStatus', {
          medicalRecordId: route.query.emrId || data,
          patientId: route.query.id,
        })
        // 取消状态
        store.dispatch('emr/setEditingStatus', false)
      }
      // 保存/提交普通病历
      const toNormalSave = async function (data) {
        toSave(data, false)
      }

      const toAsthmaSave = async function (data) {
        toSave(data, true)
      }

      const toTemplateSave = async function () {
        if (!route.query.emrId) {
          ElMessage.error('病历尚未提交，请先保存病历，再进行存档操作')
          return
        }
        common.XmLoading(true)
        const res = await saveNormalTemplate({
          medicalRecordId: route.query.emrId,
        }).catch(() => {})
        common.XmLoading(false)
        if (!res) return
        ElMessage.success('提交成功')
      }
      const initPage = function () {
        const id = route.query.emrId
        if (id) d.emrId = id
        toLoad(id)
        // 切换重置掉进度条，重置掉修改文件状态
        resetData()
      }
      const store = useStore()
      onBeforeMount(async () => {
        store.dispatch('emr/setControlDialogStatus', false)
        store.dispatch('emr/setAcuteDialogStatus', false)
        if (store.getters.emrTypes) {
          if (
            store.getters.emrActivityType ||
            store.getters.emrActivityType === 0
          ) {
            d.docType = store.getters.emrActivityType
            await store.dispatch('emr/setActivityEmrType', null)
            routerFilter({ delete: 'emrId' })
          }
          initPage()
        } else {
          const types = await store.dispatch('emr/loadEmrTypes')
          d.emrDocTypes = types
          if (!d.docType) {
            if (
              store.getters.emrActivityType ||
              store.getters.emrActivityType === 0
            ) {
              d.docType = store.getters.emrActivityType
              await store.dispatch('emr/setActivityEmrType', null)
            } else {
              // 默认新哮喘病历
              // 新
              let defaultDocType = types.find(
                (item) => item.label === '新哮喘病历'
              )
              d.docType = defaultDocType?.value || types[0].value
            }
          }
          initPage()
        }
      })

      // 修改药品使用方式1
      const modeChange = function (item) {
        d.mode = item.value
      }
      // 修改病历类型
      const { routerFilter } = filter()
      const { giveUpEditing } = emrStatus()
      const emrChange = async function (item) {
        if (route.query.emrId) {
          // raplace 会刷新路由所以放这里
          await store.dispatch('emr/setActivityEmrType', item.value)
          routerFilter({ delete: 'emrId' })
        } else {
          giveUpEditing()
            .then(async () => {
              d.docType = item.value
              await nextTick()
              initPage()
            })
            .catch(() => {})
        }
      }

      const selectTemplate = function () {
        emrRef.value.dialogClick()
      }

      // 是否导入
      const isImport = ref(false)
      const importRiskData = async function () {
        common.XmLoading(true)
        const res = await load({
          medicalRecordId: d.riskMedicalRecordId,
          patientId: props.pid,
          docType: route.query.emrId ? null : d.docType,
        }).catch(() => {
          // TODO false 去掉标志
          common.XmLoading(false)
          return
        })
        common.XmLoading(false)
        isImport.value = true
        if (emrRef.value) emrRef.value.initEmr(res.data)
      }

      const disabledTime = computed(() => {
        console.log('d.disabled || !!props.emrId =' + !!route.query.emrId)
        return d.disabled || !!route.query.emrId
      })
      async function timeChange(val) {
        // 没有保存 不参与这个逻辑
        if (d.recordDate === d.oldRecordDate) return
        common
          .syncAlert('切换后，部分逻辑会重新计算，请确认是否修改')
          .then(() => {
            // 如果确认就进行下一步
            d.oldRecordDate = d.recordDate
            routerFilter({ delete: 'emrId' })
            toLoad()
          })
          .catch(() => {
            d.recordDate = d.oldRecordDate
          })
        // 取消焦点，fix element datePicker设置时间 弹出弹窗，但是重复选择不触发change方法的问题
        let focusedElement = document.activeElement
        focusedElement.blur()
        // toLoad()
        // ageType: 患者年龄是否大等于6岁(lessThan 小于 greaterEqual 大等于)
        // 没有保存 不参与这个逻辑
        // if (!route.query.emrId) return
        // const birthday = store.getters.patientInfo.birthday
        // const ageType =
        //   diffTimesToYear(d.recordDate, birthday) >= 6
        //     ? 'greaterEqual'
        //     : 'lessThan'
        // const oldAgeType =
        //   diffTimesToYear(d.oldRecordDate, birthday) >= 6
        //     ? 'greaterEqual'
        //     : 'lessThan'
        // if (ageType !== oldAgeType) {
        //   let msg = '年龄与病历内容不符，无法修改，请新建病历。'
        //   if (oldAgeType === 'lessThan' && ageType === 'greaterEqual')
        //     msg =
        //       '当前选择的病历日期不符合学龄前期儿童(<6岁)病历范围，请新建病历。'
        //   if (oldAgeType === 'greaterEqual' && ageType === 'lessThan')
        //     msg = '当前选择的病历日期不符合学龄期儿童(≥6)病历范围，请新建病历。'
        //   d.recordDate = d.oldRecordDate
        //   // 取消焦点，fix element datePicker设置时间 弹出弹窗，但是重复选择不触发change方法的问题
        //   let focusedElement = document.activeElement
        //   focusedElement.blur()
        //   const [err, res] = await to(common.syncAlert(msg))
        // }
      }

      // 打印页面
      const medicalRecordView = ref(null); // 组件 ref
      const hideButton = ref(false); // 是否隐藏浮动按钮
      function print() {
        hideButton.value = true;
        nextTick(() => {
          new VuePrintLast({
            el: "#printDOM", // 指定要打印的元素
            preview: false,  // 开启打印预览
            openCallback: () => {},
            closeCallback: () => {
              hideButton.value = false;
            }
          });
        })
      }
      return {
        d,
        emrRef,
        toNormalSave,
        initPage,
        modeChange,
        emrChange,
        toTemplateSave,
        toAsthmaSave,
        selectTemplate,
        // 是否有风险筛查需要导入
        isHasRisk,
        // 是否风险筛查
        isRiskRx,
        importRiskData,
        timeChange,
        disabledTime,
        medicalRecordView,
        print,
        hideButton
      }
    },
  }
</script>
<style lang="scss" scoped>
  .medicalRecord-container {
    padding: 0px 22px;
    position: relative;

    .mr-header {
      .search-grip {
        margin-right: 10px;
        // padding: 10px;
        // display: flex;
        display: inline-block;
        align-items: center;
        font-size: var(--el-form-label-font-size);
        color: var(--el-text-color-regular);

        span {
          white-space: nowrap;
        }

        .el-input {
          display: inline-block;
          margin-left: 10px;
          // vertical-align: middle;
        }

        .el-select {
          margin-left: 10px;
        }

        :deep(.el-date-editor) {
          margin-left: 10px;
        }
      }

      .iconClass {
        border: 2px solid #409eff;
        display: inline-block;
        padding: 4px;
        margin-right: 2px;
        border-radius: 25px;
        vertical-align: middle;

        &.is-complete {
          border-color: var(--el-button-disabled-font-color);
        }

        // margin-bottom: ;
      }

      margin-bottom: 12px;
    }

    .footer-div {
      .el-button {
        float: right;
        margin-right: 12px;
        margin-left: 0px;
      }
    }
    .print-asthma {
      :deep(.content-wrapper) {
        line-height: 0;
      }
    }
  }
</style>
